package com.example.dorm1_demo.service;

import com.example.dorm1_demo.entity.Dormitory;
import com.example.dorm1_demo.mapper.DormitoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class DormitoryService {
    // 注入宿舍数据访问对象
    @Autowired
    private DormitoryMapper dormitoryMapper;
    // 获取所有宿舍信息
    public List<Dormitory> getAllDormitories() {
        return dormitoryMapper.selectAll();
    }
    //根据ID获取宿舍信息
    public Dormitory getDormitoryById(Integer id) {
        return dormitoryMapper.selectById(id);
    }
    // 根据宿舍号搜索宿舍
    public List<Dormitory> searchDormitoriesByNumber(String number) {
        return dormitoryMapper.selectByNumber(number);
    }
    // 根据楼栋搜索宿舍
    public List<Dormitory> searchDormitoriesByBuilding(String building) {
        return dormitoryMapper.selectByBuilding(building);
    }
    // 添加新的宿舍信息
    public boolean addDormitory(Dormitory dormitory) {
        return dormitoryMapper.insert(dormitory) > 0;
    }
    // 更新宿舍信息
    public boolean updateDormitory(Dormitory dormitory) {
        return dormitoryMapper.update(dormitory) > 0;
    }
    // 删除宿舍信息
    public boolean deleteDormitory(Integer id) {
        return dormitoryMapper.delete(id) > 0;
    }
    // 更新宿舍入住情况
    public boolean updateDormitoryOccupancy(Integer dormitoryId, boolean isAdd) {
        Dormitory dormitory = dormitoryMapper.selectById(dormitoryId);
        if (dormitory == null) {return false;}
        if (isAdd) {dormitory.setOccupied(dormitory.getOccupied() + 1);}
        else {dormitory.setOccupied(dormitory.getOccupied() - 1);}
        // 更新状态
        if (dormitory.getOccupied() == 0) {dormitory.setStatus("空宿舍");
        } else if (dormitory.getOccupied() < dormitory.getCapacity()) {dormitory.setStatus("部分入住");
        } else {dormitory.setStatus("已满");}
        return dormitoryMapper.update(dormitory) > 0;
    }
}